package com.excilys.blog.refactoring.refactored;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.excilys.blog.refactoring.GeoPoint;

class GeoPointSet implements Iterable<GeoPoint> {

    private final Set<GeoPoint> points;

    public GeoPointSet(Set<GeoPoint> points) {
        this.points = points;
    }

    public void checkPreconditions() {
        if (points == null || points.size() == 0) {
            throw new IllegalArgumentException("points set should not be null or empty");
        }
    }

    public boolean hasOnePoint() {
        return points.size() == 1;
    }

    public List<GeoPoint> copyAsList() {
        return new ArrayList<GeoPoint>(points);
    }

    public Bounds findBounds() {
        GeoPoint westernPoint = anyPoint();
        GeoPoint easternPoint = westernPoint;
        for (GeoPoint point : points) {
            if (point.isWesterOrSameButNorther(westernPoint)) {
                westernPoint = point;
            } else if (point.isEasterOrSameButSouther(easternPoint)) {
                easternPoint = point;
            }
        }
        return new Bounds(westernPoint, easternPoint);
    }

    private GeoPoint anyPoint() {
        return iterator().next();
    }

    @Override
    public Iterator<GeoPoint> iterator() {
        return points.iterator();
    }

}
